package cn.edu.hust.sse.software7.class3.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import cn.edu.hust.sse.software7.class3.entities.EBProduct;
import cn.edu.hust.sse.software7.class3.service.EBProductService;
import cn.edu.hust.sse.software7.class3.serviceImpl.EBProductServiceImpl;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class ProdServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	EBProductService ebps = new EBProductServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method.equals("delete")) {
			Long prodId = new Long(req.getParameter("prod2Delete"));
			EBProduct prod2Del = ebps.getProdById(prodId);

			ebps.deleteProduct(prod2Del);
			HttpSession session = req.getSession();
			List<EBProduct> prods = ebps.getProds();
			if (null == prods || prods.isEmpty()) {
				session.removeAttribute("prodList");
			} else {
				session.setAttribute("prodList", prods);
			}
			resp.sendRedirect("admin/productManage/watchProd.jsp");
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method.equals("addprod")) {

			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iterator = null;
			Map<String, String> fields = new HashMap<String, String>();
			Blob bImg = null;
			try {
				iterator = upload.getItemIterator(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			try {
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream stream = item.openStream();
					if (item.isFormField()) {
						fields.put(item.getFieldName(),
								IOUtils.toString(stream));
					} else {
						bImg = new Blob(IOUtils.toByteArray(stream));
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			String prodName = fields.get("prodName");
			String prodCategory = fields.get("prodCategory");
			Long prodCategoryId = new Long(prodCategory);
			Float prodLowestPrice = new Float(fields.get("prodLowestPrice"));
			Float tradingPrice = new Float(fields.get("tradingPrice"));
			Float freight = new Float(fields.get("freight"));
			Integer mount = new Integer(fields.get("mount"));
			String description = fields.get("description");
			
			EBProduct prod2Add = new EBProduct(prodName, description,
					prodCategoryId, bImg, prodLowestPrice, mount, freight,
					tradingPrice);
			prod2Add.setHightestBid(prodLowestPrice);
			ebps.addProduct(prod2Add);
			resp.sendRedirect("admin/productManage/addProd.jsp");
		} else if (method.equals("updateprod")) {
			HttpSession session = req.getSession();
			EBProduct prod = (EBProduct) session.getAttribute("updateProduct");

			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iterator = null;
			Map<String, String> fields = new HashMap<String, String>();
			Blob bImg = null;
			try {
				iterator = upload.getItemIterator(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			try {
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream stream = item.openStream();
					if (item.isFormField()) {
						fields.put(item.getFieldName(),
								IOUtils.toString(stream));
					} else {
						bImg = new Blob(IOUtils.toByteArray(stream));
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}

			Float prodLowestPrice = new Float(fields.get("prodLowestPrice"));
			Float tradingPrice = new Float(fields.get("tradingPrice"));
			Float freight = new Float(fields.get("freight"));
			Integer mount = new Integer(fields.get("mount"));
			String description = fields.get("description");

			if (prodLowestPrice != null) {
				prod.setLowestPrice(prodLowestPrice);
			}
			if (tradingPrice != null) {
				prod.setTradingPrice(tradingPrice);
			}
			if (freight != null) {
				prod.setFreight(freight);
			}
			if (mount != null) {
				prod.setMount(mount);
			}
			if (description != null) {
				prod.setProductDescription(description);
			}
			if (bImg != null &&bImg.getBytes().length > 0) {
				ImagesService is = ImagesServiceFactory.getImagesService();
				Image image = ImagesServiceFactory.makeImage(bImg.getBytes());
				Transform tf = ImagesServiceFactory.makeResize(90, 120);
				Image newImage = is.applyTransform(tf, image);
				byte[] imageData = newImage.getImageData();
				Blob blob = new Blob(imageData);
				prod.setProductImage(blob);
			}
			ebps.updateProduct(prod);
			session.setAttribute("updateProduct", prod);

			resp.sendRedirect("admin/productManage/updateProd.jsp");
		} else if (method.equals("findProd")) {
			String queryStr = req.getParameter("queryStr");
			String scope = req.getParameter("scope");
			String from = req.getParameter("from");
			String to = req.getParameter("to");
			List<EBProduct> prods = null;

			String filter = "";
			if (!queryStr.equals("")) {
				filter = "productName.startsWith(\"" + queryStr + "\")";
			} else {
				if (null != scope) {
					Float fromPrice = new Float(0);
					Float toPrice = new Float(0);
					if (!fromPrice.equals("")) {
						fromPrice = new Float(from);
					}
					if (!toPrice.equals("")) {
						toPrice = new Float(to);
					}

					if (scope.equals("low")) {
						if (fromPrice < toPrice) {
							filter += "lowestPrice >= " + fromPrice + "";
							filter += " && lowestPrice <= " + toPrice + "";
						}
					}
					if (scope.equals("bid")) {
						if (fromPrice < toPrice) {
							filter += "hightestBid >= " + fromPrice + "";
							filter += " && hightestBid <= " + toPrice + "";
						}
					}
					if (scope.equals("fre")) {
						if (fromPrice < toPrice) {
							filter += "freight >= " + fromPrice + "";
							filter += " && freight <= " + toPrice + "";
						}
					}
				}
			}
			HttpSession session = req.getSession();

			prods = ebps.getProdsByFilter(filter);
			session.setAttribute("prodList", prods);
			System.out.println(prods.size());
			resp.sendRedirect("eBusiness/prod/watchProds.jsp");
		}
	}
}
